package de.herberlin.webapp.image.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import de.herberlin.webapp.core.AbstractAction;
import de.herberlin.webapp.db.Operation;
import de.herberlin.webapp.db.Service;
import de.herberlin.webapp.image.Gallery;
import de.herberlin.webapp.image.GalleryItem;

public class GetGalleryAction extends AbstractAction implements Operation {

	
	private static final long serialVersionUID = 1L;

	private Gallery gallery=null;
	private String pageId=null;
	
	public GetGalleryAction() {
	}
	
	public GetGalleryAction(String pageId) {
		this.pageId=pageId;
	}

	@Override
	public String getPageId() {
		if (pageId==null) {
			return super.getPageId();
		} else {
			return pageId;
		}
	}
	private synchronized void loadGallery() {
		if (getPageId() ==null) {
			logger.warn("PageId must not be null!");
			return ;
		}
		Service.perform(this);
				
	}
	
	
	
	public Gallery getGallery() {
		if (gallery==null) {
			loadGallery();
		}
		return gallery;
	}

	@SuppressWarnings("unchecked")
	public void perform(EntityManager em) throws Exception {
		
		Query q=em.createQuery("select g from GalleryItem g where g.pageId=:pageId order by g.position asc");
		q.setParameter("pageId", getPageId());
		List<GalleryItem> list=(List<GalleryItem>)q.getResultList();
		
		gallery=new Gallery();
		gallery.setGalleryItems(list);

	}
}
